/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-06-26
 * Time: 10:25
 */
class Solution19 {
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,-1,1};
    //标记数组
    boolean[][] visit;
    int m,n,step,ret;
    public int uniquePathsIII(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        visit = new boolean[m][n];

        //起始位置坐标
        int beginx = 0, beginy = 0;

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                //记录步数
                if(grid[i][j] == 0) {
                    step++;
                    //记录起始位置
                }else if(grid[i][j] == 1) {
                    beginx = i;
                    beginy = j;
                }
            }
        }
        //加上初始和结束位置
        step += 2;
        visit[beginx][beginy] = true;
        dfs(grid,beginx,beginy,1);
        return ret;
    }

    void dfs(int[][] grid, int i, int j,int count) {
        if(grid[i][j] == 2) {
            if(count == step) {
                ret++;
            }
            return;
        }

        for(int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && grid[x][y] != -1) {
                visit[x][y] = true;
                dfs(grid,x,y,count+1);
                visit[x][y] = false;
            }
        }
    }
}
